package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;

    //分页查询
    @Override
    public PageResult<Clazz> pageQuery(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> pageParam = Page.of(page,pageSize);
        pageParam.addOrder(OrderItem.desc("update_time"));
        LambdaQueryWrapper<Clazz> wrapper = new LambdaQueryWrapper<Clazz>()
                .like(name!=null && !name.isEmpty(),Clazz::getName,name)
                        .between(begin!=null && end!=null,Clazz::getEndDate,begin,end);
        page(pageParam,wrapper);

        List<Clazz> clazzes = pageParam.getRecords();

        //填充班主任和状态
        Set<Integer> ids = pageParam.getRecords().stream().map(Clazz::getMasterId).collect(Collectors.toSet());
        List<Emp> emps = new ArrayList<>();
        if(ids != null){
            emps = empService.listByIds(ids);
        }
        Map<Integer, String> clazzMasters = emps.stream()
                .collect(Collectors.toMap(Emp::getId,Emp::getName));

        for (Clazz clazz : clazzes) {
            clazz.setMasterName(clazzMasters.get(clazz.getMasterId()));
            if(clazz.getEndDate().isBefore(LocalDate.now())){
                clazz.setStatus("已结课");
            } else if (clazz.getBeginDate().isAfter(LocalDate.now())) {
                clazz.setStatus("未开班");
            }else {
                clazz.setStatus("已开班");
            }
        }

        return new PageResult<>(pageParam.getTotal(), pageParam.getRecords());

    }
}
